// pages/home/classify.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,

        category_list: [],
        good_list: [],
        uid: '',
        page: 1,
        page_size: 6,
        current_index: 0,
        default_seacrhing_list: [{
            name: '寿星补汁'
        }, {
            name: '钻山风合剂'
        }, {
            name: '参茸补血酒'
        }],
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "name": "对症下药 快速选品"
        },

        noMore: false,

        type: '',

        bgcolor: '#fff',
        // 店铺详情
        shopDetail: {
            true_name: '金顶官方旗舰店',
            logo: "http://img.jin.gzzsu.com/shop/20240419/d0nzbr7u5cuvtopbc3.jpg",
            extinfo: {
                certificate_img: 'http://img.jin.gzzsu.com/shop/20240419/d0nzbr7u5cuvtopbc3.jpg'
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            uid: App.globalData.uid || util.getAppValue('userInfo').uid,
        })
        // let index = options.index
        // this.setData({
        //   current_index: index,
        // })
        this.get_category_list()
    },

    go_search() {
        wx.navigateTo({
            url: '/pages/good/search',
        })
    },

    onPageScroll: function (e) {
        // wx.getSystemInfoSync().windowHeight 系统手机窗口高度
        // 当页面滑动距离大于一屏的高度时显示回到顶部控件
        this.setData({
            ifShowTop: e.scrollTop > wx.getSystemInfoSync().windowHeight ? true : false
        });
    },


    // 查看商品详情
    go_detail(e) {
        let id = e.detail.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },

    // 请求分类
    get_category_list(index = 0) {
        let params = {
            page: this.data.page,
            limit: 15
        }

        request.post(api.category_list, params).then(res => {
            // res.reverse()
            // console.log('res', res);
            let newlist = [{
                name: '全部',
                id: '',
                visibility: 1
            }]
            newlist.push(...res)
            let type = newlist[index].id
            this.setData({
                category_list: newlist,
                type

            })
            this.get_good_list()
        })
    },

    get_good_list() {
        let params = {
            page: this.data.page,
            limit: this.data.page_size,
            type: this.data.type,
            // brand_id: 2
        }
        let list = this.data.good_list
        //  goods_list接口拿到的是redis缓存内容，查询用goodssearch
        request.post(api.goods_search, params).then(res => {
            if (res.length == 0) {
                this.setData({
                    noMore: true
                })
                util.showToast('暂无更多相关商品')
                return
            }
            for (var i = 0; i < res.length; i++) {
                let mx = parseInt(Math.random() * 10) / 10
                let youhui = res[i].sell_price * (mx * 0.04 + 0.08)
                res[i].youhui = youhui.toFixed(2)
            }
            let new_list = list.concat(res)
            this.setData({
                good_list: new_list
            })
        })
    },

    // 切换商品分类
    choosing_category(e) {
        let current_index = e.currentTarget.dataset.index
        let type = e.currentTarget.dataset.cate_id
        this.setData({
            current_index,
            type,
            page: 1,
            noMore: false,
            good_list: []
        })
        this.get_good_list()
    },

    // 商品列表组件点击加入购物车
    async cart_add(e) {
        if (!this.data.uid) {
            util.showToast('请登录后再添加购物车哦')
            return
        }
        let id = e.detail.currentTarget.dataset.id
        let goodDetail = await request.post(api.goods_details, { id })
        if (goodDetail.store_nums <= 0) {
            wx.showToast({
                title: '该商品暂无库存，请挑选别的心仪商品吧',
                icon: 'none',
                duration: 2000
            });
            return
        }

        // 筛选最低价格规格id，默认选最低规格
        let temArr = []
        goodDetail.products_array.forEach(item => {
            temArr.push(item.sell_price)
        });
        let lowestProPrice = Math.min(...temArr)
        let lowestIndex = temArr.indexOf(lowestProPrice)
        let skuid = goodDetail.products_array[lowestIndex].id
        // console.log('skuid', skuid);

        let params = {
            goods_id: id,
            uid: this.data.uid,
            goods_sku_id: skuid
        }
        let res = await request.post(api.cart_add, params)
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums

            this.handleChangeCart()
        }
        util.showToast("已加入购物车")
    },

    handleChangeCart() {
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                cartnum: App.globalData.cartnum,
                // selected: 0
            })
        }
    },

    /**
    * 页面上拉触底事件的处理函数
    */
    onReachBottom: function () {
        if (!this.data.noMore) {
            this.setData({
                page: ++this.data.page
            })
            this.get_good_list()
        }
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 自定义底部栏保证选择无误的代码
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                cartnum: App.globalData.cartnum,
                selected: 1
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        setTimeout(async () => {
            this.setData({
                noMore: false,
                page: 1,
                category_list: [],
                good_list: []
            })
            await this.get_category_list(this.data.current_index)
            wx.stopPullDownRefresh()

        }, 1800);
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})

